package logic

import (
	"context"
	"edu-pro/edurpc/edurpc"
	"edu-pro/edurpc/internal/svc"
	"edu-pro/models/cache"
	"edu-pro/models/mysql"
	"edu-pro/pkg"
	"errors"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *edurpc.UserRegisterRequest) (*edurpc.UserRegisterResponse, error) {
	// 新用户注册
	var user mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&user)
	if user.ID != 0 {
		return nil, errors.New("可直接登录")
	}
	if len(in.Password) < 6 {
		return nil, errors.New("密码必须超过6位")
	}

	//if pkg.CheckPwd(in.Password) {
	//	return nil, errors.New("密码需含数字与字母")
	//}
	smsCode, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Phone).Result()
	if smsCode != in.SmsCode {
		return nil, errors.New("短信验证码有误，请您重新输入")
	}
	user = mysql.User{
		Phone:     in.Phone,
		Password:  pkg.Md5string(in.Password),
		Nickname:  fmt.Sprintf("用户%s", in.Phone),
		AvatarUrl: "http://t2u3h1i1n.hn-bkt.clouddn.com/1cdd12d9e59f408c82ac6c8c8a75055f.jpg",
		Status:    0,
	}
	mysql.DB.Debug().Create(&user)
	return &edurpc.UserRegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
